package com.nx.biz.shopify.support;

import com.google.gson.Gson;
import com.nx.biz.shopify.api.bo.ShopifySession;
import com.nx.biz.shopify.repo.ShopifySessionRepository;
import com.nx.biz.shopify.sdk.ShopifySdk.WebhooksSdk;
import com.nx.biz.shopify.sdk.ShopifySdk.model.bo.WebHookBo;
import com.nx.biz.shopify.sdk.ShopifySdk.model.constant.TopicConstants;
import com.nx.common.tools.CheckTools;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class ShopifyInitHelper {

    private static final Gson GSON = new Gson();

    @Resource
    private ShopifyContext shopifyContext;
    @Resource
    private ShopifySessionRepository shopifySessionRepository;
    @Resource
    private WebhooksSdk webhooksSdk;
    @Autowired
    private TopicConstants topicConstants;

    @Value("${shopify.webhook.callback-url}")
    private String shopifyWebhookUrl;

    // 初始化shopify-webhook，依赖于context是否初始化完成
    @SneakyThrows
    private void initWebHook(ShopifySession shopifySession) {
        log.info("<--- [shopify-webhook]初始化开始...start");

        if (shopifyContext.getWebhookRegisterComplete(shopifySession.getShop())) {
            log.info("shopDomain：{} 的webhook已注册完成，跳过处理", shopifySession.getShop());
            return;
        }


        // 初始化待创建的topic list
        List<String> toRegTopics = new ArrayList<>();
        toRegTopics.add(TopicConstants.fulfillmentCreate);
        toRegTopics.add(TopicConstants.fulfillmentRequestCreate);
        toRegTopics.add(TopicConstants.orderCreate);
        toRegTopics.add(TopicConstants.orderUpdate);
        toRegTopics.add(TopicConstants.orderDelete);
        toRegTopics.add(TopicConstants.orderFulfilled);
        toRegTopics.add(TopicConstants.orderPaid);

        /* 查询已注册的 */
        List<WebHookBo> webHookBoList = new ArrayList<>();
        try {
            webHookBoList = webhooksSdk.listTopic(shopifySession.getShop(), shopifyContext.getApiVersion(), shopifySession.getAccessToken());
        } catch (Exception e) {
            log.error("获取已注册的webhook-topic失败，错误信息：{}", e.getMessage());
            log.error("异常堆栈：", e);
        }

        /* 检查并注册 */
        int registerCompleteCount = 0;
        for (String topic : toRegTopics) {
            boolean found = false;
            WebHookBo foundTopic = null;
            for (WebHookBo webHookBo : webHookBoList) {
                if (webHookBo.getTopic().equals(topic)) {
                    found = true;
                    foundTopic = webHookBo;
                    break;
                }
            }

            if (found) {
                log.info("init, topic [{}] 已订阅，准备取消订阅", topic);
                webhooksSdk.deleteTopic(String.valueOf(foundTopic.getId()), shopifySession.getShop(), shopifyContext.getApiVersion(), shopifySession.getAccessToken());
                log.info("init, topic [{}] 已订阅，已取消订阅", topic);
            }

            // 重新订阅
            WebHookBo webHookBo = webhooksSdk.createTopic(
                    topic,
                    shopifyWebhookUrl,
                    shopifySession.getShop(),
                    shopifyContext.getApiVersion(),
                    shopifySession.getAccessToken()
            );
            if (CheckTools.isNotNullOrEmpty(webHookBo)) {
                registerCompleteCount++;
                log.info("init, topic [{}] 未订阅，订阅成功", topic);
            } else {
                log.info("init, topic [{}] 未订阅，订阅失败", topic);
            }

            // 未订阅过topic，创建
//            if (!found) {
//                log.info("init, topic [{}] 未订阅过，准备订阅", topic);
//                try {
//                    WebHookBo webHookBo = webhooksSdk.createTopic(
//                            topic,
//                            shopifyWebhookUrl,
//                            shopifySession.getShop(),
//                            shopifyContext.getApiVersion(),
//                            shopifySession.getAccessToken()
//                    );
//                    if (CheckTools.isNotNullOrEmpty(webHookBo)) {
//                        registerCompleteCount++;
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    log.error("init, topic [{}] 未订阅过，订阅过程发生异常，错误信息：{}", topic, e.getMessage());
//                }
//            } else {
//                log.info("init, topic [{}] 已订阅，无需重复订阅", topic);
//                registerCompleteCount++;
//            }
        }
        if (registerCompleteCount == toRegTopics.size()) {
            shopifyContext.setWebhookRegisterCompleted(shopifySession.getShop());
        }
        log.info("<--- [shopify-webhook]初始化完成...success");
    }

    /**
     * 执行初始化过程
     */
    public void execInit() {
        /* 1、查询shopify会话 */
        log.info("[shopify]初始化开始...");
        List<ShopifySession> shopifySessionList = shopifySessionRepository.queryList(null);
        if (CheckTools.isNullOrEmpty(shopifySessionList)) {
            log.info("[shopify]初始化中断...error，错误信息：未查询到会话信息");
            return;
        }

        /* 2、初始化webhook */
        int index = 1;
        for (ShopifySession shopifySession : shopifySessionList) {
            log.info("--> 开始处理第[{}]个会话的webhook初始化，shopDomain：{}", index, shopifySession.getShop());
            this.initWebHook(shopifySession);
            log.info("<-- 结束处理第[{}]个会话的webhook初始化，shopDomain：{}", index, shopifySession.getShop());
            index++;
        }
        log.info("[shopify]初始化结束...");
    }

}